package com.okilo.online.app.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.view.View
import com.okilo.online.app.R
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.databinding.OkiloActPinPayStatusBinding
import com.okilo.online.app.databinding.OkiloActPinPayStatusReasonItemBinding
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.pet.OkiloLoanPet
import com.okilo.online.app.pet.view.IOkiloLoan
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2025/11/13 17:04
 * @Annotation：PIN 支付结果处理中
 */
class OkiloPinPayStatusAct: OkiloComAct(), IOkiloLoan.IOkiloPay, IOkiloLoan.IOkiloPinPayStatus {
    private var _binding: OkiloActPinPayStatusBinding? = null
    //支付
    private var payPet: OkiloLoanPet? = null
    //三方订单id
    private var thirdOrderId = ""
    //倒计时
    private var countdownTimer: OkiloPinPayStatusCountDownTimer? = null
    private var countdown = 30
    companion object {
        private const val INTENT_KEY_ORDER_ID = "thirdOrderId"
        fun start(context: Context, orderId: String, repayDate: String) {
            val intent = Intent(context, OkiloPinPayStatusAct::class.java)
            intent.putExtra(INTENT_KEY_ORDER_ID, orderId)
            context.startActivity(intent)
        }
    }

    override val pageName: String = "Pin_Payment_Page"

    override fun createOkiloContentView(): View? {
        _binding = OkiloActPinPayStatusBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        getTitleBarManager()
            .setTitleBarVisibility(View.VISIBLE)
            .setBackButtonIcon(R.mipmap.okilo_root_back_icon)
            .setRightButtonIcon(R.mipmap.okilo_root_customer_icon)
            .setTitle(getString(R.string.okilo_pin_pay_status_title))
            .setRootBackgroundColor(getColor(R.color.okilo_color_ffeff1f3))
        initOkiloPinPaySatusRefreshView()
        _binding?.okiloPinPayStatusContentLayout?.visibility = View.INVISIBLE
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
        //还款中 刷新
        _binding?.okiloPinPayStatusButtonUpdate?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOAN_PIN_PROCESS_PAYMENT_UPDATE,"TransactionId：${thirdOrderId}")
                showOkiloLoading()
                gOkiloPinPayStatusAction()
            }
        })
        //成功 - 再次申请
        _binding?.okiloPinPayStatusButtonApplyAgain?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOAN_PIN_SUCCESS_APPLY_AGAIN,"TransactionId：${thirdOrderId}")
                showOrderPaySuccessAction()
            }
        })
        //失败 - 重新发起支付
        _binding?.okiloPinPayStatusButtonMakeAgain2?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOAN_PIN_FAILED_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
                showOkiloLoading()
                payPet?.gOkiloPayLinkRequest(this@OkiloPinPayStatusAct)
            }
        })
        //还款中 - 重新发起支付
        _binding?.okiloPinPayStatusButtonMakeAgain1?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOAN_PIN_PROCESS_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
                showOkiloLoading()
                payPet?.gOkiloPayLinkRequest(this@OkiloPinPayStatusAct)
            }
        })
    }

    override fun loadOkiloData() {
        thirdOrderId = gOkiloPayThirdOrderId()
        if (payPet == null){
            payPet = OkiloLoanPet(this)
        }
        showOkiloLoading()
        gOkiloPinPayStatusAction()
    }

    /* 初始化刷新 */
    private fun initOkiloPinPaySatusRefreshView() {
        _binding?.okiloPinPayStatusRefreshLayout?.setColorSchemeResources(
            R.color.okilo_color_theme,
            R.color.okilo_color_ff6200ee)
        _binding?.okiloPinPayStatusRefreshLayout?.setOnRefreshListener {
            gOkiloPinPayStatusAction()
        }
    }


    /**
     * 支付成功 - 跳转到可申请列表
     */
    private fun showOrderPaySuccessAction(){
        //刷新流程
        publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_REFRESH))
        //返回首页
        publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_SHOW_HOME))
        OkiloActStackManager.finishAllActivity(OkiloMainAct::class.java)
    }

    /**
     * 三方订单id
     */
    private fun gOkiloPayThirdOrderId(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_ORDER_ID).toString()
    }

    /**
     * PIN 通用View
     */
    fun sOkiloPinPayStatusCommonView(data: JSONObject) {
        val binding = _binding ?: return
        binding.okiloPinPayStatusAmountText.text = data.optString("realRepayAmount","")
        binding.okiloPinPayStatusProductText.text = data.optString("product","")
//        binding.textUnit.text = data.optString("")
        binding.okiloPinPayStatusTransactionIdText.text = data.optString("transactionId","")
        binding.okiloPinPayStatusContentLayout.visibility = View.VISIBLE
    }

    /**
     * PIN 支付成功
     */
    fun sOkiloPinPayStatusSuccessView(realRepayTime: String) {
        val binding = _binding ?: return

        binding.okiloPinPayStatusIcon.setImageResource(R.mipmap.okilo_pin_pay_status_success_icon)
        binding.okiloPinPayStatusButtonUpdate.visibility = View.GONE
        binding.okiloPinPayStatusText.text = getString(R.string.okilo_pin_pay_status_payment_awesome)
        binding.okiloPinPayStatusText.visibility = View.VISIBLE
        binding.okiloPinPayStatusTipsText.text = getString(R.string.okilo_pin_pay_status_payment_success_tips)
        binding.okiloPinPayStatusTipsText.visibility = View.VISIBLE
        binding.okiloPinPayStatusTransactionIdTitleText.text = getString(R.string.okilo_pin_pay_status_pay_transaction_id)
        binding.okiloPinPayStatusTransactionIdLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusProcessedLayout.visibility = View.GONE
        binding.okiloPinPayStatusSuccessLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusSuccessTimeText.text = realRepayTime
        binding.okiloPinPayStatusFailedLayout.visibility = View.GONE

        binding.okiloPinPayStatusTipsLayout.visibility = View.GONE

        binding.okiloPinPayStatusButtonMakeAgain1.visibility = View.GONE
        binding.okiloPinPayStatusButtonMakeAgain2.visibility = View.GONE
        binding.okiloPinPayStatusButtonApplyAgain.visibility = View.VISIBLE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付失败
     */
    @SuppressLint("SetTextI18n")
    fun sOkiloPinPayStatusFailedView(data: JSONObject) {
        val binding = _binding ?: return

        binding.okiloPinPayStatusIcon.setImageResource(R.mipmap.okilo_pin_pay_status_rejected_icon)
        binding.okiloPinPayStatusButtonUpdate.visibility = View.GONE
        binding.okiloPinPayStatusText.text = getString(R.string.okilo_pin_pay_status_failed_title)
        binding.okiloPinPayStatusText.visibility = View.VISIBLE
        val failReason = data.optString("failReason","")
        if (failReason.isNotEmpty()){
            binding.okiloPinPayStatusTipsText.text = String.format(getString(R.string.okilo_pin_pay_status_failed_reason_failure),failReason)
            binding.okiloPinPayStatusTipsText.visibility = View.VISIBLE
        } else {
            binding.okiloPinPayStatusTipsText.visibility = View.GONE
        }
        binding.okiloPinPayStatusTransactionIdTitleText.text = getString(R.string.okilo_pin_pay_status_pay_id)
        binding.okiloPinPayStatusTransactionIdLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusProcessedLayout.visibility = View.GONE
        binding.okiloPinPayStatusSuccessLayout.visibility = View.GONE
        binding.okiloPinPayStatusFailedLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusFailedTimeText.text = data.optString("failedTime")

        binding.okiloPinPayStatusTipsLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusTipsTitleText.text = getString(R.string.okilo_pin_pay_status_failed_reason_title)

        val reasonList = arrayListOf<String>().apply {
            add(getString(R.string.okilo_pin_pay_status_failed_reason1))
            add(getString(R.string.okilo_pin_pay_status_failed_reason2))
            add(getString(R.string.okilo_pin_pay_status_failed_reason3))
            add(getString(R.string.okilo_pin_pay_status_failed_reason4))
            add(getString(R.string.okilo_pin_pay_status_failed_reason5))
        }
        addOkiloPinPayStatusReasonListView(reasonList)

        binding.okiloPinPayStatusButtonMakeAgain1.visibility = View.GONE
        binding.okiloPinPayStatusButtonMakeAgain2.visibility = View.VISIBLE
        binding.okiloPinPayStatusButtonApplyAgain.visibility = View.GONE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付中
     */
    fun sOkiloPinPayStatusProcessView(data: JSONObject) {
        //是否是审核账号
        val isAdmin = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接进入还款失败
            sOkiloPinPayStatusFailedView(data)
            return
        }
        val binding = _binding ?: return

        binding.okiloPinPayStatusIcon.setImageResource(R.mipmap.okilo_pin_pay_status_reviewing_icon)
        binding.okiloPinPayStatusButtonUpdate.visibility = View.VISIBLE
        binding.okiloPinPayStatusText.visibility = View.GONE
        binding.okiloPinPayStatusTipsText.visibility = View.GONE
        binding.okiloPinPayStatusTransactionIdLayout.visibility = View.GONE
        binding.okiloPinPayStatusProcessedLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusSuccessLayout.visibility = View.GONE
        binding.okiloPinPayStatusFailedLayout.visibility = View.GONE

        binding.okiloPinPayStatusTipsLayout.visibility = View.VISIBLE
        binding.okiloPinPayStatusTipsTitleText.text = getString(R.string.okilo_dlog_tips)
        val reasonList = arrayListOf<String>().apply {
            add(String.format(getString(R.string.okilo_pin_pay_status_processed_reason1),data.optString("realRepayAmount","")))
            add(getString(R.string.okilo_pin_pay_status_processed_reason1))
            add(getString(R.string.okilo_pin_pay_status_processed_reason1))
        }
        addOkiloPinPayStatusReasonListView(reasonList)

        binding.okiloPinPayStatusButtonMakeAgain1.visibility = View.VISIBLE
        binding.okiloPinPayStatusButtonMakeAgain2.visibility = View.GONE
        binding.okiloPinPayStatusButtonApplyAgain.visibility = View.GONE

        countdown = 0
        sOkiloPinPayStatusProcessButtonStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startOkiloPinPayStatusCountdownTimer()
        }
    }

    /**
     * 添加描述item
     */
    private fun addOkiloPinPayStatusReasonListView(itemList: ArrayList<String>){
        val binding = _binding ?: return
        binding.okiloPinPayStatusTipsReasonLayout.removeAllViews()
        itemList.forEach { reason ->
            val itemBinding = OkiloActPinPayStatusReasonItemBinding.inflate(layoutInflater)
            itemBinding.okiloPinPayStatusReasonText.text = reason
            binding.okiloPinPayStatusTipsReasonLayout.addView(itemBinding.root)
        }
    }

    /**
     * 开启倒计时
     */
    private fun startOkiloPinPayStatusCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 30

        if (countdownTimer == null){
            countdownTimer = OkiloPinPayStatusCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class OkiloPinPayStatusCountDownTimer(private val act: OkiloPinPayStatusAct, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.sOkiloPinPayStatusProcessButtonStatus()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showOkiloLoading()
            act.gOkiloPinPayStatusAction(false)
        }
    }

    /**
     * 设置按钮状态
     */
    private fun sOkiloPinPayStatusProcessButtonStatus(){
        val binding = _binding ?: return

        if (countdown <= 0){
            binding.okiloPinPayStatusButtonMakeAgain1.isEnabled = true
            binding.okiloPinPayStatusButtonMakeAgain1.text = String.format(getString(R.string.okilo_pin_pay_status_make_payment_again),"")
        } else {
            binding.okiloPinPayStatusButtonMakeAgain1.isEnabled = false
            binding.okiloPinPayStatusButtonMakeAgain1.text = String.format(getString(R.string.okilo_pin_pay_status_make_payment_again),"(${countdown}s)")
        }
    }

    /**
     * 再次支付结果
     */
    override fun sOkiloPayDataCallback(data: JSONObject) {
        if (data.has("thirdOrderId")){
            thirdOrderId = data.optString("thirdOrderId")
        }
        gOkiloPinPayStatusAction()
    }

    /**
     * 获取支付状态查询结果
     */
    override fun sOkiloPinPayStatusData(data: JSONObject) {
        if (data.has("transactionId")){
            thirdOrderId = data.optString("transactionId")
        }
        sOkiloPinPayStatusCommonView(data)
        // PROCESSING /SUCCEEDED /FAILED
        val status = data.optString("status")
        when(status){
            "FAILED" -> {
                sOkiloPinPayStatusFailedView(data)
            }
            "SUCCEEDED" -> {
                val realRepayTime = data.optString("realRepayTime","")
                sOkiloPinPayStatusSuccessView(realRepayTime)
            }
            else -> {
                sOkiloPinPayStatusProcessView(data)
            }
        }
    }

    /**
     * 获取支付状态
     */
    private fun gOkiloPinPayStatusAction(isStartCountdown: Boolean = true){
        payPet?.gOkiloPinPayStatusRequest(thirdOrderId, isStartCountdown,this)
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when(event.eventType){
            OkiloEventData.TYPE.OKILO_HTTP_REQUEST_ERROR -> {
                hideOkiloLoading()
            }
            else -> {

            }
        }
    }

    override fun hideOkiloLoading() {
        super.hideOkiloLoading()
        _binding?.okiloPinPayStatusRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
    }
}